package com.j4cf.lx.controller.agent;

import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.j4cf.auth.dao.entity.AuthUser;
import com.j4cf.auth.service.AuthApiService;
import com.j4cf.auth.service.AuthUserService;
import com.j4cf.common.base.*;
import com.j4cf.common.util.MD5Util;
import com.j4cf.common.util.MapUtil;
import com.j4cf.common.util.StringUtil;
import com.j4cf.common.validator.LengthValidator;
import com.j4cf.common.validator.NotNullValidator;
import com.j4cf.lx.dao.dto.LxMemberDTO;
import com.j4cf.lx.dao.entity.LxBpRecord;
import com.j4cf.lx.dao.entity.LxGoods;
import com.j4cf.lx.dao.entity.LxMemberCard;
import com.j4cf.lx.dao.entity.LxUser;
import com.j4cf.lx.service.LxAgentService;
import com.j4cf.lx.service.LxBpRecordService;
import com.j4cf.lx.service.LxMemberCardService;
import com.j4cf.lx.service.LxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: Lxmembercard controller
 * @Author: LongRou
 * @CreateDate: 2018/5/8.
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/agent/LxMemberManage")
@Api(value = "Lxmembercard控制器", description = "Lxmembercard管理")
public class LxMemberManageController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LxMemberManageController.class);
    @Autowired
    private AuthApiService authApiService;
    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private LxMemberCardService lxMemberCardService;
    @Autowired
    private LxAgentService lxAgentService;
    @Autowired
    private LxUserService lxUserService;
    @Autowired
    private LxBpRecordService lxBpRecordService;

    @ApiOperation(value = "根据ID修改-Lxmembercard-信息", notes = "根据ID修改-Lxmembercard-信息")
    @RequiresRoles(value = {"agent"})
    @RequestMapping(value = "/insertMember", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult insertMember(@RequestBody Map<String, Object> params) {
        AuthUser authUser = new AuthUser();
        LxMemberCard lxMemberCard = new LxMemberCard();
        LxUser lxUser = new LxUser();
        MapUtil.mapToBean(params,authUser);
        MapUtil.mapToBean(params,lxMemberCard);
        MapUtil.mapToBean(params,lxUser);
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(lxMemberCard.getMemberCardId() + "", new NotNullValidator("基本信息"))
                .on(authUser.getUsername(), new LengthValidator(6,20,"会员信息"))
                .on(authUser.getPassword(), new LengthValidator(6,20,"密码"))
                .on(authUser.getPhone(), new LengthValidator(11,11,"电话号码"))
                .on(authUser.getRealname(), new NotNullValidator("真实姓名"))
                .on(lxUser.getAreaId()+"", new NotNullValidator("用户区域"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        AuthUser _authUser = authApiService.selectAuthUserByUsername(authUser.getUsername());
        if (null != _authUser) {
            return new BaseResult(BaseResultEnum.ERROR, "会员已存在");
        }
        lxUser.setRecommendId(1);
        if (!StringUtils.isBlank(params.get("recommendName")+"")){
            AuthUser __authUser = authApiService.selectAuthUserByUsername(params.get("recommendName")+"");
            if (null != __authUser && null != lxUserService.selectById(__authUser.getUserId())) {
                lxUser.setRecommendId(__authUser.getUserId());
            }else {
                return new BaseResult(BaseResultEnum.ERROR, "推荐人不存在");
            }
        }
        LxMemberCard _lxMemberCard = lxMemberCardService.selectById(lxMemberCard.getMemberCardId());
        if (null != _lxMemberCard && _lxMemberCard.getAgentUserId().equals(getUserId()) && _lxMemberCard.getState() == 0) {
            _lxMemberCard.setConsume(lxMemberCard.getConsume());
            List<LxGoods> goodsList = JSONObject.parseArray(lxMemberCard.getConsume(), LxGoods.class);
            final Double[] consunmPrice = {0d};
            goodsList.forEach(good -> {
                consunmPrice[0] += (good.getShopPrice()*good.getSold());
            });
            if (consunmPrice[0] < _lxMemberCard.getConsumeMin()) {
                return new BaseResult(BaseResultEnum.ERROR, "购买的商品没有达到该会员类型的最低标准");
            }
            _lxMemberCard.setConsumePrice(consunmPrice[0]);
            if (lxAgentService.insertMember(authUser,_lxMemberCard,lxUser)) {
                return new BaseResult(BaseResultEnum.SUCCESS, "绑定成功");
            }
        }
        return new BaseResult(BaseResultEnum.ERROR, "插入失败");
    }
    @ApiOperation(value = "根据ID重置会员密码", notes = "根据ID重置会员密码")
    @RequiresRoles(value = {"agent"})
    @RequestMapping(value = "/resetMemberPass", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult resetMemberPass(@RequestBody LxMemberCard entity) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(entity.getMemberCardId() + "", new NotNullValidator("基本信息"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        LxMemberCard lxMemberCard = lxMemberCardService.selectById(entity.getMemberCardId());
        if (null != lxMemberCard && lxMemberCard.getAgentUserId().equals(getUserId()) && lxMemberCard.getState() == 1) {
            AuthUser authUser = authUserService.selectById(lxMemberCard.getUserId());
            authUser.setPassword(MD5Util.md5("123456" + authUser.getSalt()));
            if (authUserService.updateById(authUser)){
                return new BaseResult(BaseResultEnum.SUCCESS, "重置密码成功，请及时登录修改");
            }
        }
        return new BaseResult(BaseResultEnum.ERROR, "修改失败");
    }


    @ApiOperation(value = "查询-Lxmembercard-信息分页", notes = "查询-Lxmembercard-信息分页")
    @RequiresRoles(value = {"agent"})
    @RequestMapping(value = "/selectPage", method = RequestMethod.GET)
    public BaseResult<Page<LxMemberDTO>> selectPage(@RequestParam Map<String, Object> params) {
        params.put("agent_user_id", getUserId());
        BaseQuery BaseQuery = new BaseQuery<LxMemberCard>(params);
        try {
            Page<LxMemberCard> tPage = new Page<>(BaseQuery.getPage(), BaseQuery.getSize());
            tPage.setSearchCount(true);
            return new BaseResult(BaseResultEnum.SUCCESS, lxMemberCardService.selectLxMemberPage(tPage, BaseQuery.getEntityWrapper()));
        } catch (Exception e) {
            return new BaseResult(BaseResultEnum.ERROR, "请检查参数是否正确");
        }
    }
    @ApiOperation(value = "根据会员账号重置会员密码",notes = "根据会员账号重置会员密码")
    @RequiresRoles(value = {"agent"})
    @RequestMapping(value = "/resetMemberPassword" ,method = RequestMethod.PUT ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult resetMemberPassword(@RequestBody AuthUser entity) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(entity.getPassword(), new LengthValidator(5, 32, "密码"))
                .on(entity.getUsername(), new NotNullValidator("代理商账号"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        entity.setSalt(salt);
        entity.setPassword(MD5Util.md5(entity.getPassword() + entity.getSalt()));
        AuthUser authUser = authUserService.selectOne(new EntityWrapper<AuthUser>().eq("username",entity.getUsername()));
        if (null == authUser){return new BaseResult(BaseResultEnum.ERROR, "账号不存在");}
        LxMemberCard lxMemberCard = lxMemberCardService.selectOne(new EntityWrapper<LxMemberCard>().eq("user_id",authUser.getUserId()).eq("agent_user_id",getUserId()));
        if (null == lxMemberCard){return new BaseResult(BaseResultEnum.ERROR, "非法的操作");}
        authUser.setSalt(salt);
        authUser.setPassword(entity.getPassword());
        if (authUserService.updateById(authUser)){
            return new BaseResult(BaseResultEnum.SUCCESS, "密码重置成功！");
        }else {
            return new BaseResult(BaseResultEnum.ERROR, "密码重置失败！");
        }
    }

    @ApiOperation(value = "查询-下属会员LxBpRecord-信息分页", notes = "查询-下属会员LxBpRecord-信息分页")
    @RequiresRoles(value = {"agent"})
    @RequestMapping(value = "/selectRecordPage", method = RequestMethod.GET)
    public BaseResult<Page<LxBpRecord>> selectRecordPage(@RequestParam Map<String, Object> params) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(params.get("user_id")+"", new NotNullValidator("必要参数"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        BaseQuery BaseQuery = new BaseQuery<LxBpRecord>(params);
        try {
            Page<LxBpRecord> tPage = new Page<>(BaseQuery.getPage(), BaseQuery.getSize());
            tPage.setSearchCount(true);
            return new BaseResult(BaseResultEnum.SUCCESS, lxBpRecordService.selectPage(tPage, BaseQuery.getEntityWrapper()));
        } catch (Exception e) {
            return new BaseResult(BaseResultEnum.ERROR, "请检查参数是否正确");
        }
    }
    //待写
    @ApiOperation(value = "查询-下属会员信息", notes = "查询-下属会员信息")
    @RequiresRoles(value = {"agent"})
    @RequestMapping(value = "/selectMemberInfo", method = RequestMethod.GET)
    public BaseResult<Page<LxBpRecord>> selectMemberInfo(@RequestParam Map<String, Object> params) {
        params.put("agent_user_id", getUserId());
        BaseQuery BaseQuery = new BaseQuery<LxMemberCard>(params);
        try {
            Page<LxMemberCard> tPage = new Page<>(BaseQuery.getPage(), BaseQuery.getSize());
            tPage.setSearchCount(true);
            return new BaseResult(BaseResultEnum.SUCCESS, lxMemberCardService.selectLxMemberPage(tPage, BaseQuery.getEntityWrapper()));
        } catch (Exception e) {
            return new BaseResult(BaseResultEnum.ERROR, "请检查参数是否正确");
        }
    }

    private Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        AuthUser authUser = authApiService.selectAuthUserByUsernameByCache(username);
        if (null != authUser) {
            return authUser.getUserId();
        } else {
            return -1;
        }
    }
}